package io.awen.modules.sign.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.awen.common.utils.PageUtils;
import io.awen.common.utils.Query;
import io.awen.modules.sign.dao.SignUnitDao;
import io.awen.modules.sign.entity.SignUnitEntity;
import io.awen.modules.sign.qo.SignUnitQo;
import io.awen.modules.sign.service.SignUnitService;
import io.awen.modules.sys.entity.SysUserEntity;
import io.awen.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("signUnitService")
public class SignUnitServiceImpl extends ServiceImpl<SignUnitDao, SignUnitEntity> implements SignUnitService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(SignUnitQo qo) {
        IPage<SignUnitEntity> page = this.page(
                new Query<SignUnitEntity>().getPage(qo),
                new QueryWrapper<SignUnitEntity>().lambda()
                        .le(qo.getStartTime() != null, SignUnitEntity::getCreateTime, qo.getStartTime())
                        .ge(qo.getEndTime() != null, SignUnitEntity::getCreateTime, qo.getEndTime())
                        .and(StringUtils.isNotBlank(qo.getKey()), wrapper -> {
                            wrapper.like(SignUnitEntity::getName, qo.getKey())
                                    .or()
                                    .like(SignUnitEntity::getCreditCode, qo.getKey());
                        })
                        .orderByDesc(SignUnitEntity::getId)
        );

        for (SignUnitEntity unit : page.getRecords()) {
            SysUserEntity user = sysUserService.getById(unit.getPrincipalId());
            unit.setPrincipal(user);
        }

        return new PageUtils(page);
    }

}